package filter;

import org.apache.shiro.config.Ini;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import pojo.Menu;
import service.ShiroService;

import java.util.List;

public class MyChainDefinitions implements FactoryBean<Ini.Section> {
    @Autowired
    private ShiroService shiroService;

    private String filterChainDefinitions;//配置文件中的静态过滤链

    public void setFilterChainDefinitions(String filterChainDefinitions) {
        this.filterChainDefinitions = filterChainDefinitions;
    }

    //get.html= authc,roles[test,admin]
    //del.html= authc,roles[test]
    @Override
    public Ini.Section getObject() throws Exception {
        Ini ini = new Ini();
        ini.load(filterChainDefinitions);//加载配置文件中的静态过滤链
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {//如果原来没有过滤链，就重新定义一个
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        List<Menu> menus = shiroService.getMenuPerms();
        for (Menu menu : menus) {
            String url = menu.getUrl();
            List<String> roles = menu.getRoles();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("roles[");
            String str = "";
            if (roles != null && roles.size() > 0) {
                for (String role : roles) {
                    stringBuilder.append(role).append(",");
                }
                str = stringBuilder.substring(0, stringBuilder.length() - 1);
            }
            str += "]";
            System.out.println(str);
            section.put(url, str);
        }
        return section;
    }

    @Override
    public Class<?> getObjectType() {
        return this.getClass();
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
